<template>
  <div class="orders-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="未支付" name="unpaid">
        <order-table :orders="unpaidOrders" @cancel="handleCancel" @pay="handlePay" />
      </el-tab-pane>
      <el-tab-pane label="已支付" name="paid">
        <order-table :orders="paidOrders" @cancel="handleCancel" />
      </el-tab-pane>
      <el-tab-pane label="历史订单" name="history">
        <order-table :orders="historyOrders" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { getOrders, cancelOrder, payOrder } from '@/api/orders'
import OrderTable from '@/components/OrderTable.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const authStore = useAuthStore()
const activeTab = ref('unpaid')

const orders = ref([])

const fetchOrders = async () => {
  try {
    const response = await getOrders()
    orders.value = response
  } catch (error) {
    console.error(error)
  }
}

fetchOrders()

const unpaidOrders = computed(() => {
  return orders.value.filter(o => o.order_status === 'unpaid')
})

const paidOrders = computed(() => {
  return orders.value.filter(o => o.order_status === 'paid')
})

const historyOrders = computed(() => {
  return orders.value.filter(o => o.order_status === 'used' || o.order_status === 'canceled')
})

const handleCancel = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要取消订单吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await cancelOrder(orderId)
    ElMessage.success('取消申请已提交，等待审核')
    fetchOrders()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
    }
  }
}

const handlePay = async (orderId) => {
  try {
    await payOrder(orderId)
    ElMessage.success('支付成功')
    fetchOrders()
  } catch (error) {
    console.error(error)
  }
}
</script>

<style scoped>
.orders-container {
  padding: 20px;
}
</style>